/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PackageMaker.Maker;

import PackageMaker.Config.*;
import JAppToolKit.*;
import PackageMaker.UI.PKGMakerUI;
import java.awt.datatransfer.*;
import java.io.*;
import java.util.*;

/**
 *
 * @author wcss
 */
public class ShPackageMaker {

    private static String packageMakerBufferDir = "%HOME%/.packageBuilderBuffers";
    private static String packageInstallerUrl = "%APPDIR%/sourceFiles/installer.tar.gz";
    private static String packageJre32Url = "%APPDIR%/sourceFiles/jre732.tar.gz";
    private static String packageJre64Url = "%APPDIR%/sourceFiles/jre764.tar.gz";

    /**
     * @return the packageInstallerUrl
     */
    public static String getPackageInstallerUrl() {
        return packageInstallerUrl.replace("%APPDIR%", PKGMakerUI.appRunDir);
    }

    /**
     * @return the packageJre32Url
     */
    public static String getPackageJre32Url() {
        return packageJre32Url.replace("%APPDIR%", PKGMakerUI.appRunDir);
    }

    /**
     * @return the packageJre64Url
     */
    public static String getPackageJre64Url() {
        return packageJre64Url.replace("%APPDIR%", PKGMakerUI.appRunDir);
    }

    /**
     * @return the packageMakerBufferDir
     */
    public static String getPackageMakerBufferDir() {
        return packageMakerBufferDir.replace("%HOME%", JAppToolKit.JRunHelper.getUserHomeDirPath());
    }
    private String bufferName = "";
    private Boolean addJRESupports = false;
    private ProjectModel projectObj = null;
    private String shBufferDirUrl = "";
    private String dataDirUrl = "";
    private String readyDirUrl = "";
    private String resultDirUrl = "";
    private Boolean is32Installer = false;
    private String filesDirUrl = "";

    /**
     * 构造函数
     *
     * @param addJREPackage
     * @param pkgName
     */
    public ShPackageMaker(Boolean is32inst, Boolean addJREPackage, String bufName) {
        is32Installer = is32inst;
        this.setAddJRESupports(addJREPackage);
        this.setBufferName(bufName);
    }

    /**
     * @return the addJRESupports
     */
    public Boolean getAddJRESupports() {
        return addJRESupports;
    }

    /**
     * @param addJRESupports the addJRESupports to set
     */
    public void setAddJRESupports(Boolean addJRESupports) {
        this.addJRESupports = addJRESupports;
    }

    /**
     * 初始化缓存目录
     */
    public void initBufDir(ProjectModel project) throws Exception {
        projectObj = project;
        if (projectObj != null) {
            String bufferDir = ShPackageMaker.getPackageMakerBufferDir() + "/" + this.getBufferName();
            if (new File(bufferDir).exists()) {
                JAppToolKit.JRunHelper.runSysCmd("rm -rf " + bufferDir);
            }
            new File(bufferDir).mkdirs();
            shBufferDirUrl = bufferDir;

            dataDirUrl = bufferDir + "/data";
            new File(dataDirUrl).mkdirs();
            readyDirUrl = bufferDir + "/ready";
            new File(readyDirUrl).mkdirs();
            resultDirUrl = bufferDir + "/result";
            new File(resultDirUrl).mkdirs();
        } else {
            throw new Exception("project is empty!");
        }
    }

    /**
     * 复制并解压到相关目录
     *
     * @param pkgfile
     * @param installerDir
     */
    public static void copyPackageTo(String pkgFile, String installerDir) throws Exception {
        File ff = new File(pkgFile);
        if (ff.exists()) {
            JAppToolKit.JRunHelper.runSysCmd("cp " + pkgFile + " " + installerDir + "/" + ff.getName());
            ArrayList<String> scripts = new ArrayList<String>();
            scripts.add("cd " + installerDir);
            scripts.add("tar xvf " + ff.getName());
            scripts.add("rm -rf " + ff.getName());
            JAppToolKit.JDataHelper.writeAllLines(JAppToolKit.JRunHelper.getCmdRunScriptBufferDir() + "/copyinstallerscript.sh", scripts);
            JAppToolKit.JRunHelper.runSysCmd("chmod +x " + JAppToolKit.JRunHelper.getCmdRunScriptBufferDir() + "/copyinstallerscript.sh");
            JAppToolKit.JRunHelper.runSysCmd(JAppToolKit.JRunHelper.getCmdRunScriptBufferDir() + "/copyinstallerscript.sh");
        } else {
            throw new Exception("source package is not!");
        }
    }

    /**
     * 复制安装程序相关数据
     */
    private void copyInstallerFiles() throws Exception {
        filesDirUrl = this.dataDirUrl + "/data";
        String installer = this.dataDirUrl + "/installer";
        String jrerun = this.dataDirUrl + "/jrerun";

        new File(filesDirUrl).mkdirs();
        new File(installer).mkdirs();
        new File(jrerun).mkdirs();

        copyPackageTo(ShPackageMaker.getPackageInstallerUrl(), installer);
        
        if (getAddJRESupports()) {
            if (this.getIs32Installer()) {
                copyPackageTo(ShPackageMaker.getPackageJre32Url(), jrerun);
            } else {
                copyPackageTo(ShPackageMaker.getPackageJre64Url(), jrerun);
            }
            
            JAppToolKit.JDataHelper.writeAllLines(this.dataDirUrl + "/" + ShPackageScriptMaker.installerStartupScriptName, ShPackageScriptMaker.makeInstallerStartupScriptsWithJre());
        }else
        {
            JAppToolKit.JDataHelper.writeAllLines(this.dataDirUrl + "/" + ShPackageScriptMaker.installerStartupScriptName, ShPackageScriptMaker.makeInstallerStartupScripts());
        }
    }

    /**
     * 生成数据包
     */
    public void makePackages() throws Exception {
        if (getProjectObj() != null) {
            String installScripts = getProjectObj().packagePostInstFile;
            FilesModel[] team = getProjectObj().packageFiles;
            if (team != null) {
                copyInstallerFiles();
                File fff = new File(filesDirUrl + "/data");
                fff.mkdirs();
                makeInstallerConfigFile();
                for (FilesModel fm : team) {
                    if (fm.copyType == FilesModel.copyFile) {
                        if (new File(fm.sourcePath).exists())
                        {
                            
                        }
                    } else {
                    }
                }
            } else {
                throw new Exception("file list is empty!");
            }
        } else {
            throw new Exception("project object is empty!");
        }
    }

    /**
     * 生成安装配置文件
     */
    private void makeInstallerConfigFile() throws Exception 
    {
        PackageInstaller.Config.PackageInstallerConfig pic = new PackageInstaller.Config.PackageInstallerConfig();
        pic.setPackageName(getProjectObj().packageName);
        pic.setTitleText(getProjectObj().packageShowTitleText);
        pic.setPackageVersion(getProjectObj().packageVersion);
        pic.setLicenseFile("license.txt");
        pic.setHomepage(getProjectObj().packageHomepage);
        pic.setLogoImage("logo.png");
        pic.setFinishScriptFile("install.sh");
        pic.setRemoveScriptFile("remove.sh");
        pic.setManager(getProjectObj().packageMaintainer);
        pic.setOwner(getProjectObj().packageOriginalMaintainer);
        pic.setTopFlag(getProjectObj().packageTopFlagText);
        pic.setWelcome(getProjectObj().packageWelcomeText);
        PackageInstaller.Config.PackageInstallerConfig.save(pic, filesDirUrl + "/config.xml");
        
        //复制安装后脚本
        File instFile = new File(getProjectObj().packagePostInstFile);
        if (instFile.exists())
        {
            JAppToolKit.JRunHelper.runSysCmd("cp " + instFile.getAbsolutePath() + " " + filesDirUrl + "/install.sh");
            JAppToolKit.JRunHelper.runSysCmd("chmod +x " + filesDirUrl + "/install.sh");
            JAppToolKit.JDataHelper.writeAllLines(filesDirUrl + "/remove.sh", new String[]{ "" });
        }else
        {
            JAppToolKit.JDataHelper.writeAllLines(filesDirUrl + "/install.sh", new String[]{ "" });
            JAppToolKit.JDataHelper.writeAllLines(filesDirUrl + "/remove.sh", new String[]{ "" });
        }
        
        //复制许可文件
        File licenseFile = new File(getProjectObj().packageLicenseInfoFile);
        if (licenseFile.exists())
        {
            JAppToolKit.JRunHelper.runSysCmd("cp " + licenseFile.getAbsolutePath() + " " + filesDirUrl + "/license.txt");
        }else
        {
            JAppToolKit.JDataHelper.writeAllLines(filesDirUrl + "/license.txt", new String[]{ "" });
        }
    }

    /**
     * @return the projectObj
     */
    public ProjectModel getProjectObj() {
        return projectObj;
    }

    /**
     * @return the bufferName
     */
    public String getBufferName() {
        return bufferName;
    }

    /**
     * @param bufferName the bufferName to set
     */
    public void setBufferName(String bufferName) {
        this.bufferName = bufferName;
    }

    /**
     * @return the shBufferDirUrl
     */
    public String getShBufferDirUrl() {
        return shBufferDirUrl;
    }

    /**
     * @return the is32Installer
     */
    public Boolean getIs32Installer() {
        return is32Installer;
    }

    /**
     * @return the filesDirUrl
     */
    public String getFilesDirUrl() {
        return filesDirUrl;
    }
}